package 剑指offer;

/**
 * @description:
 * @author: ywk
 * @date: 2021-02-16
 */
public class 将字符串转化为整数 {
    /**
     * @param str string字符串
     * @return int整型
     */
    public static int atoi(String str) {
        // write code here
        int val = 0;
        if (str == null) {
            return val;
        }
        str = str.trim();
        if (str.equals("")) {
            return val;
        }
        char[] arr = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == '+' || arr[i] == '-') {
                sb.append(arr[i]);
            } else if (arr[i] >= '0' && arr[i] <= '9') {
                sb.append(arr[i]);
            } else {
                break;
            }
        }
        str = sb.toString();
        try {
            val = Integer.parseInt(str);
        } catch (Exception e) {
            if (str.charAt(0) == '-') {
                return Integer.MIN_VALUE;
            } else {
                return Integer.MAX_VALUE;
            }
        }
        return val;
    }

    public static void main(String[] args) {
        System.out.println(atoi("     -117e40091539"));
    }
}
